#include "RecordBuffer.h"

#ifndef ZERO
	#define ZERO 0
#endif

RecordBuffer::RecordBuffer()
	: handler(ZERO),
	offset(ZERO),
	record(NULL),
	size(ZERO)
{
}


RecordBuffer::~RecordBuffer()
{
	handler = ZERO;
	offset = ZERO;
	if(record != NULL)
		delete []record;
	record = NULL;
	size = ZERO;
}

void RecordBuffer::set(int h, int pos, char* ptr, unsigned int sizePtr)
{
	if(h > ZERO && pos >= ZERO && ptr != NULL && sizePtr > ZERO)
	{
		handler = h;
		offset = pos;
		if(record != NULL)
			delete []record;
		record = new char[sizePtr];
		memcpy(record, ptr, sizePtr);
		size = sizePtr;
	}
}

void RecordBuffer::get(int &h, int &pos, char* ptr, unsigned int &sizePtr)
{
	if(handler > ZERO && offset >= ZERO && size > ZERO && ptr != NULL)
	{
		h = handler;
		pos = offset;
		memcpy(ptr, record, size);
		sizePtr = size;
	}
}

void RecordBuffer::setKey(int h, int pos)
{
	if(h > ZERO && pos >= ZERO)
	{
		handler = h;
		offset = pos;
	}
}

void RecordBuffer::getKey(int &h, int &pos)
{
	if(handler > ZERO && offset >= ZERO)
	{
		h = handler;
		pos = offset;
	}
}

unsigned int RecordBuffer::getSize()
{
	return size;
}

bool RecordBuffer::equal(Data* data)
{
	int idHandler = ZERO;
	int pos = ZERO;

	if(data != NULL)
	{
		((RecordBuffer*)data)->getKey(idHandler, pos);
		return (idHandler == this->handler && pos == this->offset);
	}
	return false;
}

void RecordBuffer::copy(Data** data)
{
	if(data != NULL && (*data) != NULL)
		((RecordBuffer*)(*data))->set(this->handler, this->offset, this->record, this->size);	
}

Data* RecordBuffer::allocate()
{
	Data* data = new RecordBuffer();
	this->copy(&data);
	return data;
}

void RecordBuffer::print()
{
	char* ptr = new char[size + 1];
	ptr[size + 1] = '\0';
	memcpy(ptr, record, size);
	std::cout << "HANDLER: " << handler << std::endl;
	std::cout << "OFFSET: " << offset << std::endl;
	std::cout << "RECORD: " << ptr << std::endl;
	std::cout << "SIZE: " << size << std::endl;
}






